<template>
  <el-dialog v-model="isVisable" :title="title" @close="resetData">
    <el-form :model="formData" :rules="rules" label-width="100px" ref="formRel">
      <el-form-item label="账号" prop="username">
        <el-input v-model="formData.username" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="nickName">
        <el-input v-model="formData.nickName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="formData.password"
          autocomplete="off"
          :disabled="editId !== 0"
        ></el-input>
      </el-form-item>
      <el-form-item label="备注" prop="note">
        <el-input type="textarea" v-model="formData.note" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="是否启用">
        <el-radio v-model="formData.status" :label="1" size="large">是</el-radio>
        <el-radio v-model="formData.status" :label="0" size="large">否</el-radio>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button>取消</el-button>
        <el-button type="primary" @click="submitFn">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang='ts'>
import { reactive, ref, watch } from 'vue';
import { GetUserInfoById, RegUserApi, UpdateUserInfoByIdApi } from '@/request/api'
import { ElForm, ElMessage, ElMessageBox } from 'element-plus';
type FormInstance = InstanceType<typeof ElForm>
const emit = defineEmits(["myclose"])

const props = defineProps({
  // 这个属性决定了dialog是否显示
  isVisable: {
    type: Boolean, // 一定写大写
    default: false
  },
  editId: {
    type: Number,
    default: 0,
  },
  title: {
    type: String,
    default: "标题"
  }
})

const checkEmail = (rule: any, value: string, cb: any) => {
  // 判断邮箱是否满足固定格式
  if (!/^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\.)+[a-z]{2,}$/.test(value)) {
    return cb(new Error('请输入正确的邮箱格式'));
  }

  cb()
}

const rules = reactive({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    }
  ],
  email: [
    {
      required: true,
      message: '请输入正确邮箱',
      trigger: 'blur',
    },
    {
      validator: checkEmail,
      trigger: 'blur',
    }
  ]
})

let formData = reactive<IUserModel>({
  createTime: '',
  email: '',
  icon: '',
  id: 0,
  loginTime: '',
  nickName: '',
  note: '',
  password: '',
  status: 1,
  username: ''
})


const formRel = ref<FormInstance>()
const isSuccess = ref<Boolean>(false)

const resetData = () => {
  // 清空数据
  for (let key in formData) {
    formData[key] = ''
  }
  // 通知父组件也把对应的数据重置
  emit('myclose', isSuccess.value);
  // 操作完了，把数据重置
  isSuccess.value = false;
}

const userConfirm = (msg: string) => {
  return ElMessageBox.confirm(
    msg,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      // type: 'warning',
    }
  )
}

const submitFn = () => {
  // 再次验证表单
  formRel.value?.validate()?.then((bool: boolean) => {
    // if(!bool)
    if (props.editId === 0) {
      // 添加
      return userConfirm('你确定要添加该用户吗？')
    } else {
      // 修改
      return userConfirm('你确定要修改该用户吗？')
    }
  }).then(() => {
    if (props.editId === 0) {
      // 发请求添加用户
      return RegUserApi(formData)
    } else {
      return UpdateUserInfoByIdApi(formData)
    }
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success(res.message);
      isSuccess.value = true;
      resetData();
    } else {
      ElMessage.error(res.message)
    }
  })

}

watch(() => props.editId, (newValue) => {
  // 当newValue不是0的时候，就是点击了编辑
  if (newValue === 0) return;
  GetUserInfoById(newValue).then(res => {
    if (res.code === 200) {
      // 请求成功后，渲染
      // for (let key in res.data) {
      //   formData[key] = res.data[key]
      // }
      Object.assign(formData, res.data); // 其实就是上面的forin的操作
    } else {
      ElMessage.error(res.message)
    }
  })
})

</script>
<style lang="less" scoped>
</style>